﻿@inherits BootstrapChildContentComponentBase
@namespace Bootstrap5

<div class="accordion-item @(GetCssClassString())" @attributes="AdditionalAttributes">
    <h2 class="accordion-header">
        <button class="accordion-button @(GetCollapsedClass())" type="button" data-bs-toggle="collapse" data-bs-target="#@(Alias)">
            @if(HeadContent is null){
                @Title
            }else{
                @HeadContent
            }
        </button>
    </h2>
    <div id="@Alias" class="accordion-collapse collapse @(GetActiveClass())" data-bs-parent="@(IsAlwaysOpen)">
        <div class="accordion-body">
            @ChildContent
        </div>
    </div>
</div>


@code{


    [CascadingParameter] Accordion Parent { get; set; }
    [Parameter] public string Title { get; set; }
    [Parameter] public RenderFragment HeadContent { get; set; }
    [Parameter] public string Alias { get; set; }=$"accortion-item-{Guid.NewGuid()}";
    internal bool Active { get; set; }

    protected override void OnInitialized()
    {
        if(Parent is null)
        {
            throw new CascadingValueNullException(nameof(AccordionItem), nameof(Accordion));
        }

        Parent.AddComponent(this);
    }

    string GetActiveClass() => Active ? "show" : null;
    string GetCollapsedClass() => !Active ? "collapsed" : null;
    string IsAlwaysOpen
    {
        get
        {
            if (!Parent.AlwaysOpen)
            {
                return $"#{Parent.Alias}";
            }
            return null;
        }
    }
}